using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MauiBuilder.Services;
using Microsoft.Maui.Controls;

namespace MauiBuilder.ViewModels
{
    /// <summary>
    /// 设置页面的视图模型
    /// 管理应用设置相关的功能
    /// </summary>
    public partial class SettingsViewModel : BaseViewModel
    {
        /// <summary>
        /// <summary>
        /// 主题管理器实例
        /// </summary>
        protected readonly ThemeManager ThemeManager = ThemeManager.Instance;

        /// <summary>
        /// 日志管理器实例
        /// </summary>
        private readonly LogManager _logManager = LogManager.Instance;
        
        /// <summary>
        /// 设置管理器实例
        /// </summary>
        private readonly SettingsManager _settingsManager = SettingsManager.Instance;

        /// <summary>
        /// 通知开关状态
        /// 控制应用是否发送系统通知
        /// </summary>
        [ObservableProperty]
        private bool _notificationsEnabled = true;
        
        /// <summary>
        /// 声音开关状态
        /// 控制通知和应用操作是否播放声音
        /// </summary>
        [ObservableProperty]
        private bool _soundEnabled = true;
        
        /// <summary>
        /// 震动开关状态
        /// 控制通知和应用操作是否启用震动反馈
        /// </summary>
        [ObservableProperty]
        private bool _vibrationEnabled = true;

        /// <summary>
        /// 深色模式开关状态
        /// 控制应用界面主题（浅色/深色）
        /// </summary>
        [ObservableProperty]
        private bool _isDarkTheme;

        /// <summary>
        /// 通知间隔时间（分钟）
        /// 设置应用发送通知的时间间隔
        /// </summary>
        [ObservableProperty]
        private int _notificationInterval = 5;
        
        /// <summary>
        /// 选择的语言
        /// 应用界面显示语言设置
        /// </summary>
        [ObservableProperty]
        private string _selectedLanguage = "中文";

        /// <summary>
        /// 构造函数，初始化设置视图模型
        /// </summary>
        public SettingsViewModel()
        {
            _logManager.LogInfo("SettingsViewModel 初始化");
            // 初始化主题状态
            IsDarkTheme = ThemeManager.IsDarkTheme();
            LoadSettings();
        }
        

        #region 计算属性

        /// <summary>
        /// 可选语言列表
        /// </summary>
        public List<string> AvailableLanguages => new() { "中文", "English", "日本語" };

        /// <summary>
        /// 通知间隔选项
        /// </summary>
        public List<int> NotificationIntervals => new() { 1, 3, 5, 10, 15, 30 };

        #endregion

        #region 命令

        /// <summary>
        /// 保存设置命令
        /// </summary>
        [RelayCommand]
        private async Task OnSaveSettings()
        {
            try
            {
                _logManager.LogInfo($"保存设置 - 通知:{NotificationsEnabled}, 声音:{SoundEnabled}, 震动:{VibrationEnabled}");
                
                // 应用主题设置
                ThemeManager.SwitchTheme(IsDarkTheme);
                
                // 保存所有设置
                SaveSettings();
                
                await AppShell.DisplayAlertAsync(
                    "设置保存", 
                    "您的设置已成功保存！");
            }
            catch (Exception ex)
            {
                _logManager.LogInfo($"保存设置失败: {ex.Message}");
                await AppShell.DisplayAlertAsync("错误", $"保存设置失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 重置设置命令
        /// </summary>
        [RelayCommand]
        private async Task OnResetSettings()
        {
            bool confirm = await AppShell.DisplayConfirmAsync(
                "重置设置", 
                "确定要重置所有设置为默认值吗？", 
                "确定", 
                "取消");
                
            if (confirm)
            {
                // 重置设置为默认值
                ResetToDefaultSettings();
                
                // 应用主题设置
                ThemeManager.SwitchTheme(IsDarkTheme);
                
                _logManager.LogInfo("设置已重置为默认值");
                
                var shell = Shell.Current;
                if (shell != null)
                {
                    await shell.DisplayAlert(
                        "重置完成", 
                        "所有设置已恢复为默认值", 
                        "确定");
                }
            }
        }

        /// <summary>
        /// 清除缓存命令
        /// </summary>
        [RelayCommand]
        private async Task OnClearCache()
        {
            bool confirm = await AppShell.DisplayConfirmAsync(
                "清除缓存", 
                "确定要清除应用缓存吗？这将删除临时文件和日志。");
                
            if (confirm)
            {
                try
                {
                    // 清理日志文件
                    _logManager.CleanupOldLogs(0);
                    
                    await AppShell.DisplayAlertAsync(
                        "清除完成", 
                        "应用缓存已清除");
                        
                    _logManager.LogInfo("用户手动清除了应用缓存");
                }
                catch (Exception ex)
                {
                    await AppShell.DisplayAlertAsync("错误", $"清除缓存失败: {ex.Message}");
                }
            }
        }

        #endregion
        
        #region 私有方法
        
        /// <summary>
        /// 加载设置
        /// </summary>
        private void LoadSettings()
        {
            try
            {
                // 加载主题设置
                IsDarkTheme = _settingsManager.LoadSetting(SettingsManager.DarkModeKey, false);
                
                // 加载其他设置
                NotificationsEnabled = _settingsManager.LoadSetting(SettingsManager.NotificationsEnabledKey, true);
                SoundEnabled = _settingsManager.LoadSetting(SettingsManager.SoundEnabledKey, true);
                VibrationEnabled = _settingsManager.LoadSetting(SettingsManager.VibrationEnabledKey, true);
                NotificationInterval = _settingsManager.LoadSetting(SettingsManager.NotificationIntervalKey, 5);
                SelectedLanguage = _settingsManager.LoadSetting(SettingsManager.SelectedLanguageKey, "中文");
            }
            catch (Exception ex)
            {
                _logManager.LogError($"加载设置失败: {ex.Message}");
                // 使用默认值
                ResetToDefaultSettings();
            }
        }
        
        /// <summary>
        /// 保存设置
        /// </summary>
        private void SaveSettings()
        {
            try
            {
                // 保存主题设置
                _settingsManager.SaveSetting(SettingsManager.DarkModeKey, IsDarkTheme);
                
                // 保存其他设置
                _settingsManager.SaveSetting(SettingsManager.NotificationsEnabledKey, NotificationsEnabled);
                _settingsManager.SaveSetting(SettingsManager.SoundEnabledKey, SoundEnabled);
                _settingsManager.SaveSetting(SettingsManager.VibrationEnabledKey, VibrationEnabled);
                _settingsManager.SaveSetting(SettingsManager.NotificationIntervalKey, NotificationInterval);
                _settingsManager.SaveSetting(SettingsManager.SelectedLanguageKey, SelectedLanguage);
            }
            catch (Exception ex)
            {
                _logManager.LogError($"保存设置失败: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 重置为默认设置
        /// </summary>
        private void ResetToDefaultSettings()
        {
            NotificationsEnabled = true;
            SoundEnabled = true;
            VibrationEnabled = true;
            IsDarkTheme = false;
            NotificationInterval = 5;
            SelectedLanguage = "中文";
        }

        #endregion
    }
}